package ph.com.gs3.formalistics.view.document.abstractfields;

import java.util.Timer;
import java.util.TimerTask;

import ph.com.gs3.formalistics.model.vo.business.form.FormFieldData;
import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public abstract class TextTypeFieldView extends AbstractFieldView {
	protected FormFieldData formField;

	private Timer timer = new Timer();
	private final long ON_CHANGE_DELAY = 1000; // Milliseconds

	private EditText editTextValueField;
	private boolean changeListenerInitialized = false;

	public TextTypeFieldView(Context context, FormFieldData formField) {
		super(context, formField.getId());
		super.setEnabled(formField.isEnabled());

		this.formField = formField;
	}

	@Override
	protected void initializeChangeListener() {

		if (changeListenerInitialized) {
			return;
		}

		final Context contextReference = getContext();
		editTextValueField.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

			@Override
			public void afterTextChanged(final Editable s) {
				timer.cancel();
				timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						((Activity) contextReference).runOnUiThread(new Runnable() {

							@Override
							public void run() {
								notifyValueChanged();
							}
						});
					}
				}, ON_CHANGE_DELAY);
			}
		});

		changeListenerInitialized = true;
	}

	@Override
	public void showError(String errorMessage) {
		editTextValueField.setError(errorMessage);
	}

	public EditText getEditTextValueField() {
		return editTextValueField;
	}

	public void setEditTextValueField(EditText editTextValueField) {
		this.editTextValueField = editTextValueField;
	}

}
